/*
 * jsmodel.1.0.0.js
 * A plugin that updates a jQuery object representing a MVC ViewModel with the latest changes made to the DOM.
 *  
 * Licensed under MIT license
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright (c) 2014 Chad Kuehn
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a 
 * copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
 * IN THE SOFTWARE.
 */

 (function ($) {
     var pluginName = "JSModel";

     $.fn[pluginName] = function (methodOrOptions) {
         if (methods[methodOrOptions]) {
             return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
         } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
             return methods.init.apply(this, arguments);
         } else {
             $.error('Method ' + methodOrOptions + ' does not exist in ' + pluginName);
         }
     };

     var methods = {
         init: function (options) {
             var newoptions = {
                 url: "" //defaults
             }

             for (var prop in options) {
                 for (var newprop in newoptions) {
                     if (prop.toUpperCase() == newprop.toUpperCase()) {
                         newoptions[newprop] = options[prop];
                         break;
                     }
                 }
             }
             this.settings = newoptions;

             return this;
         },
         refresh: function () {

             var obj = {};

             for (var key in this[0]) {
                 var fld = $("[name='" + key + "']");


                 var type = "";
                 if (fld.is("input")) {
                     type = fld.attr("type");
                 } else if (fld.is("select")) {
                     type = "select";
                 } else if (fld.is("textarea")) {
                     type = "textarea";
                 }

                 switch (type) {
                     case "select":
                     case "textarea":
                     case "text":
                     case "password":
                     case "hidden":
                     case undefined:
                         if ($.isArray(this[0][key])) {
                             this[0][key] = fld.map(function () {
                                 return this.value;
                             }).get();
                         } else {
                             this[0][key] = fld.val();
                         }
                         break;
                     case "radio":
                         this[0][key] = fld.closest(":checked").val();
                         break;
                     case "checkbox":
                         this[0][key] = fld.closest(":checked").map(function () {
                             return this.value;
                         }).get();
                         break;
                 }

                 var chks = [];

                 $("[name ^= '" + key + "['][name *= ']'").each(function () {

                     var fld = $(this);
                     var name = fld.attr("name");
                     var val = fld.val();

                     if (fld.is("input")) {
                         if (fld.attr("type") == "checkbox") {
                             if (fld.is(":checked")) {
                                 chks.push(name);
                             }
                             return;
                         }
                     }
                     if (chks.indexOf(name) > -1) {
                         val = "true";
                     }

                     if (!isNaN(val)) {
                         if (val.indexOf(".") > -1) {
                             val = parseInt(val, 10);
                         } else {
                             val = parseFloat(val, 10);
                         }
                     } else if ((val == "true") || (val == "false")) {
                         val = (val == "true" ? true : false);
                     }
                     var regexp = /\[(\d)\]/g;
                     var match = regexp.exec(name);
                     var idxs = [];
                     while (match != null) {
                         idxs.push(parseInt(match[1], 10));
                         match = regexp.exec(name);
                     }

                     var regexp = /\.([^/[]+)/g;
                     var match = regexp.exec(name);
                     var props = [];
                     while (match != null) {
                         props.push(match[1]);
                         match = regexp.exec(name);
                     }
                     if (idxs.length != props.length) {
                         return;
                     }
                     props.unshift(key);
                     var last = obj;

                     for (var propLoop = 0; propLoop < props.length; propLoop++) {
                         var prop = props[propLoop];
                         var lastIteration = false;
                         if (propLoop == props.length - 1) {
                             lastIteration = true;
                         }
                         if (lastIteration) {
                             last[prop] = val;
                             return;
                         }
                         var idx = -1;
                         if (!lastIteration) {
                             idx = idxs[0];
                             idxs.shift();
                         }
                         if (!(prop in last)) {
                             last[prop] = [];
                         }
                         last = last[prop];


                         for (var x = last.length; x < (idx + 1); x++) {
                             last.push({});
                         }
                         last = last[idx];
                     }
                 });
             }

             for (var key in obj) {
                 this[0][key] = obj[key];
             }

             if (this.settings.url != "") {
                 var newmodel = $.ajax({
                     url: this.settings.url,
                     type: "POST",
                     async: false, // synchronous
                     contentType: "application/json;charset=utf-8;",
                     dataType: "json",
                     data: JSON.stringify(this[0])
                 }).responseText;

                 this[0] = JSON.parse(newmodel);
             }
         }
     };

 }(jQuery));